// 登录与注册模块
import { reqGetCode, reqUserInfo, reqUserLogin, reqUserOut, reqUserRegister } from "@/api"
import { lowerFirst } from "lodash"
import {setToken, removeToken} from '@/utils/token'
const state = {
    code: '',
    token: localStorage.getItem('TOKEN'),
    userInfo:{}
}
const mutations = {
    GETCODE(state,code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    CLEAR(state) {
        // 把仓库中相关信息清空
        state.token = ''
        state.userInfo = {}
        // 本地存储清空
        removeToken()
    }
}
const actions = {
    // 获取验证码
    async getCode({ commit }, phone) {
        // 获取验证码这个接口，是把验证码返回，一般是把验证码直接发到用户手机上
        let result = await reqGetCode(phone)
        console.log(result)
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户注册
    async userRegister({ commit }, data) {
        let result = await reqUserRegister(data)
        // console.log(result);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户登录
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        // console.log(result);
        // 服务器下发的token，是用户唯一标识符（uuid）
        // 将来经常通过带token向服务器要用户信息进行展示
        if (result.code == 200) {
            commit('USERLOGIN', result.data.token)
            // 持久化存储token
            localStorage.setItem("TOKEN",result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 获取登录信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            // 提交用户信息
            commit('GETUSERINFO', result.data) 
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async userLoginOut({ commit }) {
        let result = await reqUserOut()
        if (result.code == 200) {
            // 在mutations里面清除state，action里面不能操作state
            commit("CLEAR")
            return 'ok'
        } else {
            return Promise.reject(new Error('false'))
        }
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}